package com.xteam.xnetworkdisk.utils;

import com.xteam.xnetworkdisk.constant.Constant;
import com.xteam.xnetworkdisk.utilsinterface.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.*;

@Component
public class FileLocalUtils implements FileUtils {

    private static final String DIRECTORY_PATH = System.getProperty("user.home") + File.separator + "xnetworkdisk";
    private static final String FILE_PATH = DIRECTORY_PATH + File.separator + "file";
    private final RedisUtils redisUtils;

    public FileLocalUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }


    @Override
    public String copyFile(String bucketName, String oldFileName) {
        try {
            Path sourcePath = Paths.get(FILE_PATH, bucketName, oldFileName);
            if (Files.notExists(sourcePath)) {
                throw new FileNotFoundException("源文件不存在：" + sourcePath);
            }

            String newFileName = System.currentTimeMillis() + oldFileName.substring(oldFileName.lastIndexOf("."));
            Path targetPath = Paths.get(FILE_PATH, bucketName, newFileName);
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);

            return newFileName;
        } catch (IOException e) {
            throw new RuntimeException("复制文件失败：" + e.getMessage(), e);
        }
    }

    public String copyFile(String bucketName, String oldFileName,String newFileName) {
        try {
            Path sourcePath = Paths.get(FILE_PATH, bucketName, oldFileName);
            if (Files.notExists(sourcePath)) {
                throw new FileNotFoundException("源文件不存在：" + sourcePath);
            }
            Path targetPath = Paths.get(FILE_PATH, bucketName, newFileName);
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);

            return newFileName;
        } catch (IOException e) {
            throw new RuntimeException("复制文件失败：" + e.getMessage(), e);
        }
    }

    @Override
    public String uploadFile(MultipartFile file, String bucketName, String suffix) {
        try {
            String fileName = System.currentTimeMillis() + suffix;
            Path filePath = Paths.get(FILE_PATH, bucketName, fileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            return fileName;
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败：" + e.getMessage(), e);
        }
    }

    @Override
    public String uploadFile(InputStream file, String bucketName, String suffix, Long fileSize, String contentType) {
        try {

            String fileName = System.currentTimeMillis() + suffix;
            Path filePath = Paths.get(FILE_PATH, bucketName, fileName);
            Files.copy(file, filePath, StandardCopyOption.REPLACE_EXISTING);

            return fileName;
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败：" + e.getMessage(), e);
        }
    }

    @Override
    public boolean deleteFile(String fullPath) {
        String[] strings = parseBucketAndFilename(fullPath);
        String fileName = strings[1];
        String fullPathR = getFullPath(fileName);

        System.out.println(fileName + "  " + fullPathR);
        try {
            Path filePath = Paths.get(fullPathR);
            return Files.deleteIfExists(filePath);
        } catch (IOException e) {
            throw new RuntimeException("删除文件失败：" + e.getMessage(), e);
        }
    }

    @Override
    public String[] parseBucketAndFilename(String fullPath) {
        String path = fullPath.replaceAll("^[a-zA-Z]+://[^/]+/", "");
        String[] parts = path.split("/", 2);
        String bucketName = parts[0];
        String filename = (parts.length > 1) ? parts[1] : "";
        return new String[]{bucketName, filename};
    }

    @Override
    public String uploadFile(InputStream inputStream, String bucketName, String fileName, String contentType) throws Exception {
        try {
            Path filePath = Paths.get(FILE_PATH, bucketName, fileName);
            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
            return fileName;
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败：" + e.getMessage(), e);
        }
    }

    @Override
    public String generatePresignedUrl(String fullPath, String filenameR) {
        // 对于本地文件系统，不需要生成预签名 URL
        String[] strings = Tools.extractFilename(fullPath);
        return fullPath;
    }

    @Override
    public InputStream getFileInputStreamFromDisplayPath(String displayPath) {
        try {
            Path filePath = Paths.get(displayPath);
            return Files.newInputStream(filePath);
        } catch (IOException e) {
            throw new RuntimeException("获取文件输入流失败：" + e.getMessage(), e);
        }
    }

    /**
     * 获取文件的输入流，用于预览
     *
     * @param fullPath 文件的完整路径
     * @return 文件的输入流
     * @throws RuntimeException 如果文件读取失败
     */
    public InputStream getFilePreviewInputStream(String fullPath) {
        System.out.println("开始获取输出流");
        try {
            Path filePath = Paths.get(fullPath);
            if (Files.notExists(filePath)) {
                throw new FileNotFoundException("文件不存在：" + filePath);
            }
            return Files.newInputStream(filePath);
        } catch (IOException e) {
            throw new RuntimeException("获取文件输入流失败：" + e.getMessage(), e);
        }
    }

    public String getFullPath(String fileName) {
        return FILE_PATH + File.separator + Constant.USER_FILE_BUKET + File.separator + fileName;
    }
    public String getFullPathAvator(String fileName) {
        return FILE_PATH + File.separator + Constant.USER_AVATAR_BUKET + File.separator + fileName;
    }
    public String getFullPathBackground(String fileName) {
        return FILE_PATH + File.separator + Constant.USER_BACKGROUND_BUKET + File.separator + fileName;
    }
    public String getFullPathTS(String fileName) {
        return FILE_PATH + File.separator + Constant.USER_TS_BUKET + File.separator + fileName;
    }

    public void generateM3U8(String fileName, String md5Value){


        String destDir = FILE_PATH + File.separator + Constant.USER_TS_BUKET + File.separator;
        String fullPath = getFullPath(fileName);
        VideoUtil.generateM3U8Local(fullPath,destDir,fileName);

        String[] strings = Tools.splitFileName(fileName);
        String fileNameR = strings[0];
        //构建m3u8文件名称
        String newFileNameR = fileNameR + ".m3u8";
        String fullPathTS = getFullPathTS(newFileNameR);

        VideoUtil.generateM3U8External(fullPathTS,destDir,fileNameR);

//        try (InputStream filePreviewInputStream = getFilePreviewInputStream(fullPath)){
//            VideoUtil.generateM3U8(filePreviewInputStream,destDir,fileName);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
    }

}
